import {
  getInvestFlowInvestBaseCcaByMguId,
  getInvestFlowQuery,
  getOpPermissionsTaskDetail,
  getProjectCapitalPlanQuery,
  getProjectPrjProjectInvestmentIdByInvestmentId,
  getProjectProjectQuery,
  getWorkflowApprovalHistoryProcessInstanceProcessInstanceIdByProcessInstanceId,
  IGetInvestFlowQueryRes,
  IGetProjectPrjLlpProjectBaseRes
} from '@/api';
import { isApprovalHandler } from '@/components/business/Approval/approval-helper/useMode';
import { useUser } from '@/hooks/useUser';
import { newToString } from '@/utils/string';
import list from '@/views/after-investment-management/risk/list';
import { assign, isBoolean } from 'lodash-es';
import { defineStore } from 'pinia';

type TInvestFlowInstDto = Required<Required<IGetInvestFlowQueryRes>['investFlowInstDto']>;
type TTaskInstDto = Required<TInvestFlowInstDto['stepInstDtos'][0]>['taskInstDtos'][0];

export interface IExtraTaskInfo {
  // 是否审批流当前处理人
  isHandler?: boolean | null;
  // 是否当前任务发起者
  isTaskInitHandler?: boolean | null;
  // 驳回可修改状态
  isRejectedModify?: boolean | null;
  // 阶段状态
  stepStatus?: 'INIT' | 'DOING' | 'FINISH';
}
export type TTaskItem = Array<TTaskInstDto & IExtraTaskInfo>;

export interface IMguProjectInfo {
  // mgu项目信息
  mguProjectInfo: {
    projectId: string;
    projectNo: string;
    ccaId: string;
    drcNo: string;
    mguId: string;
    llpId?: number;
    prjBase: IGetProjectPrjLlpProjectBaseRes;
  };
}

interface IOperationRecord {
  tabName: string;
  entSearchParams: any;
  mguSearchParams: any;
  partnerSearchParams?: any;
  platformTabName: string;
  platformSideSearchParams: any;
  storeSideSearchParams: any;
}

interface IExpandProcessStore extends IMguProjectInfo {
  // 拓展流程信息
  investFlowInstDto: TInvestFlowInstDto;
  // 是否全部可保存
  allowSaveFinish: 'NONE' | 'CCA' | 'MGU' | 'ALL';
  // 九宫格loading
  loading: boolean;
  // 拓展流程首页操作记录
  operationRecord: IOperationRecord;
  entId?: number;
  /* 九宫格查看详情权限,默认为 true，除了 AO、品牌端-节点企业 、品牌端IO门店通过接口调用查询 */
  isDetailVisible: boolean;
  counselorSelectorOptions: Array<any>;
}

let resolveHandleList: IFunction[] = [];
let isFetched = false;

const executeResolveHandle = () => {
  while (resolveHandleList.length) {
    resolveHandleList.shift()?.();
  }
};
const getBaseData = async (projectNo: string) => {
  console.log('projectNo', projectNo);
  const projectProjectInfo = await getProjectProjectQuery({
    page: 0,
    size: 30,
    projectNoList: projectNo
  });
  const prjBase = projectProjectInfo.content?.[0];
  const projectCapitalPlan = await getProjectCapitalPlanQuery({ projectNoList: projectNo });
  prjBase.capitalPlanList = projectCapitalPlan.content;
  prjBase.projectAssociatesDateInfoDto = {
    associatesType: prjBase?.associatesType,
    investPeriods: prjBase?.investPeriods,
    openingDatePlan: prjBase?.associatedDate,
    openingDateActual: prjBase?.associatedDate,
    beginAssociatesDateActual: prjBase?.associatedDate,
    beginAssociatesDatePlan: prjBase?.associatedDate
  };
  return prjBase;
};
export const useExpandProcessStore = defineStore('expandProcessStore', {
  state(): IExpandProcessStore {
    return {
      investFlowInstDto: {} as TInvestFlowInstDto,
      isDetailVisible: true,
      allowSaveFinish: 'NONE',
      loading: false,
      mguProjectInfo: {
        projectId: '',
        projectNo: '',
        ccaId: '',
        mguId: '',
        drcNo: '',
        prjBase: {}
      },
      entId: 0,
      operationRecord: {
        tabName: 'ent',
        entSearchParams: {},
        mguSearchParams: {},
        platformTabName: 'platformSide',
        platformSideSearchParams: {},
        storeSideSearchParams: {}
      },
      counselorSelectorOptions: []
    };
  },
  persist: {
    enabled: true,
    strategies: [
      {
        paths: ['operationRecord']
      }
    ]
  },
  getters: {
    taskList() {
      let taskList: TTaskItem = [];
      this.investFlowInstDto?.stepInstDtos?.map((stepInst) => {
        taskList?.push(
          ...(stepInst?.taskInstDtos || []).map((item) => {
            return {
              stepStatus: stepInst?.stepStatus,
              ...item
            };
          })
        );
      });
      return taskList;
    }
  },
  actions: {
    updateOperationRecord(operationRecord: IOperationRecord) {
      assign(this.operationRecord, operationRecord);
    },
    updateCounselorSelectorOptions(counselorSelectorOptions: Array<any>) {
      assign(this.counselorSelectorOptions, counselorSelectorOptions || []);
    },
    async getProjectIdByInvestmentId(investmentId?: string) {
      if (!investmentId) return;
      const prj = await getProjectPrjProjectInvestmentIdByInvestmentId({ investmentId });
      if (prj) {
        this.mguProjectInfo.projectId = newToString(prj?.id);
        this.mguProjectInfo.ccaId = newToString(prj?.ccaId);
        this.mguProjectInfo.drcNo = newToString(prj?.drcNo);
        this.mguProjectInfo.mguId = newToString(prj?.mguId);
        // this.mguProjectInfo.llpId = newToString(prj?.llpId);
        this.mguProjectInfo.projectNo = newToString(prj?.projectNo);
        const projectNo = this.mguProjectInfo.projectNo;
        if (projectNo) {
          const prjBase = await getBaseData(projectNo);
          this.mguProjectInfo.prjBase = prjBase;
          console.log(prjBase, 'projectProjectInfo');
        }
        // if (this.mguProjectInfo.projectId) {
        //   this.mguProjectInfo.prjBase = await getProjectPrjLlpProjectBase({
        //     llpId: '1',
        //     projectId: this.mguProjectInfo.projectId
        //   });
        //   console.log(this.mguProjectInfo.prjBase, 'projectProjectInfo');
        // }
      } else {
        this.mguProjectInfo.prjBase = {};
      }
    },
    async getInvestFlowQueryMethod(id: string, unLoading?: boolean) {
      if (!id || id === 'NaN' || id === 'undefined') return;
      isFetched = false;
      if (!isBoolean(unLoading) || !unLoading) {
        this.loading = true;
      }
      try {
        const userData = useUser();
        const info = await getInvestFlowQuery({ id });
        const investmentType = info.investFlowInstDto?.investmentType as string;
        if (['AO', 'MGU', 'PLATFORM_IO'].includes(investmentType)) {
          await this.getProjectIdByInvestmentId((info.investFlowInstDto?.id ?? '') + '');
        }
        /* 获取节点企业信息（补充协议没有对应的项目信息，无法获取节点企业id =》 @getProjectIdByInvestmentId） */
        if (['MGU_SUP_PROTOCOL', 'PLATFORM_IO_SUP_PROTOCOL'].includes(info.investFlowInstDto?.investmentType as string)) {
          const ccaEnt = await getInvestFlowInvestBaseCcaByMguId({
            mguId: info.investFlowInstDto?.entId + ''
          });
          this.mguProjectInfo.ccaId = ccaEnt.ccaEntId + '';
        }
        /*  AO、品牌端-节点企业 、品牌端IO门店通过接口调用查询当前用户是否有权限查看该拓展流程的详情 */
        if (['AO', 'MGU', 'CCA'].includes(investmentType)) {
          const permissionGroupNameMap: IRecordValue<string> = {
            AO: 'MGU_AO_TASK_DETAIL',
            MGU: 'MGU_IO_TASK_DETAIL',
            CCA: 'ENT_IO_TASK_DETAIL'
          };
          this.isDetailVisible = await getOpPermissionsTaskDetail({
            investId: id,
            permissionGroupName: permissionGroupNameMap[investmentType]
          });
        }

        for (const stepInst of info.investFlowInstDto?.stepInstDtos ?? []) {
          for (const taskInst of (stepInst.taskInstDtos as TTaskItem) ?? []) {
            const { processInst = '', handlerType, handlerId, stepConfigId, taskConfigId, taskStatus } = taskInst ?? {};
            if (taskStatus === 'DOING' && processInst) {
              // 根据审批进度进行中的待办进行操作按钮显示状态设置
              taskInst.isHandler = await isApprovalHandler(processInst);
            }
            // 没有审批流，判断是否为任务发起者
            if (!taskInst.isHandler && taskInst.isHandler !== false) {
              if (handlerType === 'USER') {
                if (handlerId === userData.value.userId) {
                  taskInst.isTaskInitHandler = true;
                }
              } else {
                if (userData.value.roles?.some((role) => role.roleCode === handlerId)) {
                  taskInst.isTaskInitHandler = true;
                }
              }
            }

            // 当前任务处理人
            const isCurrentTaskHandler = taskInst.isHandler || taskInst.isTaskInitHandler;

            if (isCurrentTaskHandler) {
              if ([104, 105, 106].includes(stepConfigId ?? 0)) {
                const processInstanceId = info.investFlowInstDto?.stepInstDtos
                  ?.find((item) => item.stepConfigId === 108)
                  ?.taskInstDtos?.find((item) => item.taskConfigId === 1014)?.processInst;
                if (processInstanceId) {
                  getWorkflowApprovalHistoryProcessInstanceProcessInstanceIdByProcessInstanceId({
                    processInstanceId
                  }).then((res) => {
                    // 在驳回状态时对应任务可修改
                    taskInst.isRejectedModify =
                      res?.approvalConclusion === 'REJECTED' || res?.approvalConclusion === 'REVOKED';
                  });
                }
              }
              // 门店坐标确认任务
              if (taskConfigId === 2018) {
                taskInst.isRejectedModify = true;
              }
            }
          }
        }
        this.investFlowInstDto = (info.investFlowInstDto! as any) || {};
        this.entId = this.investFlowInstDto.entId;
        this.allowSaveFinish = info.allowSaveFinish ?? 'NONE';
        executeResolveHandle();
        isFetched = true;
        return info;
      } finally {
        this.loading = false;
      }
    },
    // 刷新项目信息
    refreshPrjBase() {
      if (!this.mguProjectInfo.projectId) return;
      if (!this.mguProjectInfo.projectNo) return;
      getBaseData(this.mguProjectInfo.projectNo).then((prjBase) => {
        this.mguProjectInfo.prjBase = prjBase;
        console.log(prjBase, 'projectProjectInfo-refreshPrjBase');
      });
      // getProjectPrjLlpProjectBase({
      //   llpId: '1',
      //   projectId: this.mguProjectInfo.projectId
      // }).then((res) => {
      //   this.mguProjectInfo.prjBase = res;
      // });
    },
    setTaskProcessInstanceIdById(id: number, processInstanceId: string) {
      for (const stepInst of this.investFlowInstDto?.stepInstDtos ?? []) {
        for (const taskInst of stepInst?.taskInstDtos ?? []) {
          if (taskInst.id === id) {
            taskInst.processInst = processInstanceId;
            break;
          }
        }
      }
    },
    onDataLoad() {
      return new Promise<void>((resolve) => {
        if (isFetched) {
          resolve();
          return;
        }
        resolveHandleList.push(resolve);
      });
    },
    initData(value = false) {
      isFetched = value;
      /* 离开页面销毁当前初始化的拓展流程信息 */
      if (value === false) {
        this.investFlowInstDto = {} as TInvestFlowInstDto;
        this.entId = 0;
      }
    }
  }
});

export const useBatchStore = defineStore('BatchStore', {
  state() {
    return {
      sourceList: [],
      checkedList: []
    };
  },
  actions: {
    setSourceList(list: []) {
      this.sourceList = list;
    },
    setCheckedList(list: []) {
      this.checkedList = list;
    }
  }
});

// 旧接口
// "id"
// "projectNo"
// "projectName"
// "projectDesc" 0
// "llpId"
// "ccaId"
// "planId"
// "groupId" 0
// "mguId"
// "ownerId" 0
// "targetCycleType"
// "targetCycleCount" 0
// "targetCycleUnit" 0
// "targetInvestAmount"
// "targetInvestAmountMgu" 0
// "targetIrr" 0
// "targetProfit" 0
// "realIrr" 0
// "realProfit" 0
// "realTotalPayback" 没有用
// "assessmentFlag"
// "assessmentDesc"
// "minTotalPayBack" 没有用
// "delayShareRate" 没有用
// "fundClearCycleUnit" 没有用
// "fundClearCycleIndex" 没有用
// "fundClearCycleWorkType" 没有用
// "projectStatus"
// "evaluationId"
// "capitalAttribute" 没有用
// "survivalPeriod" 没有用
// "breakEvenPoint" 没有用
// "capitalPlanList" list
// "projectAssociatesDateInfoDto" obj
// "projectDetailFrocastDataVO" obj 没有用

// 旧接口 使用的字段 没有返回的  -------- 看这里
// "id"
// "assessmentFlag"
// "assessmentDesc"
// "capitalPlanList" list
// "projectAssociatesDateInfoDto" obj

// "planId" 都是调其他接口
// "projectName" 没用?

// "projectNo" 有返回
// "llpId" 0
// "ccaId" 有返回
// "mguId" 有返回
// "targetCycleType" 有返回
// "targetInvestAmount" 有返回
// "projectStatus" 有返回
// "evaluationId" 有返回

// 新接口
// "projectNo"
// "ccaId"
// "mguId"
// "mguEnterName"
// "targetCycleType"
// "targetCycleCount"
// "targetCycleUnit"
// "targetBeginDate"
// "targetExitDate"
// "targetInvestAmount"
// "targetInvestAmountMgu"
// "targetInvestDate"
// "issueDate"
// "targetIrr"
// "realIrr"
// "evaluationId"
// "drcNo"
// "drcType"
// "projectStatus"
// "exitTime"
// "associatesType"
// "investPeriods"
// "associatedDate"
